package com.dao.impl;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dao.BookShopDao;
import com.exception.BookStockException;
import com.exception.UserAccountException;

@Repository
public class BookShopDaoImpl implements BookShopDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	//为什么hibernatetemplate类和hibernateDaoSupport，不推荐使用。
	//因为这样会导致dao和spring的api进行耦合，可移植性变差
	//private HibernateTemplate hibernateTemplate;
	
	//hibernate的使用,应该使用getcurrentsession获取当前线程的session
	private Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public Double findBookPriceByIsbn(String isbn) {
		// TODO Auto-generated method stub
		String hql="select b.price from Book b where b.isbn=?";
		Query query=getSession().createQuery(hql).setString(0, isbn);
		return (Double) query.uniqueResult();
	}

	@Override
	public void updateBookStock(String isbn) {
		// TODO Auto-generated method stub
		//验证库存是否充足
		String hql2="select b.stock from Book b where b.isbn=?";
		int stock=(int) getSession().createQuery(hql2).setString(0, isbn).uniqueResult();
		if(stock==0){
			throw new BookStockException("库存不足!");
		}
		String hql="update Book b set b.stock=b.stock-1 where b.isbn=?";
		getSession().createQuery(hql).setString(0, isbn).executeUpdate();
	}

	@Override
	public void updateUserAccount(String username, Double price) {
		// TODO Auto-generated method stub
		//验证余额是否足够
		String hql2="select a.balance from Account a where a.userName=?";
		Double balance=(Double) getSession().createQuery(hql2).setString(0, username).uniqueResult();
		if(balance< price){
			throw new UserAccountException("余额不足！");
		}
		String hql="update Account a set a.balance='" + (balance-price) + "' where a.userName=?";
		getSession().createQuery(hql).setDouble(0, price).setString(0, username).executeUpdate();
	}

}
